package com.hoshino.momochi.aspect;

import com.hoshino.momochi.model.domain.HistoryRead;
import com.hoshino.momochi.service.HistoryReadService;
import com.hoshino.momochi.util.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;

@Aspect
@Component
@Slf4j
public class HistoryAspect {

    @Autowired
    private HistoryReadService historyReadService;

    private final String USER_ID = CodeEnum.USERID.getMessage();
    private final String BLOG_ID = CodeEnum.BLOGID.getMessage();

    @Pointcut("@annotation(com.hoshino.momochi.annotation.History)")
    public void pointCut() {
        // 切入点
    }

    /**
     * 记录 访问历史记录
     *
     * @param joinPoint
     */
    @After("pointCut()")
    public void after(JoinPoint joinPoint) {
        // 获取请求
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        Long uid = (Long) request.getAttribute(USER_ID);
        Long bid = (Long) request.getAttribute(BLOG_ID);

        if (Objects.nonNull(uid) && Objects.nonNull(bid)) {
            HistoryRead historyRead = new HistoryRead();
            historyRead.setCreateTime(new Date());
            historyRead.setUserId(uid);
            historyRead.setBlogId(bid);
            Long id = historyReadService.checkHaveHistory(uid, bid);
            if (id != null) {
                historyReadService.delHistory(uid, new ArrayList<>(){
                    {add(id);}
                });
            }
            historyReadService.addHistoryRead(historyRead);
        }
    }
}
